package primary;

import interfaces.DALException;

import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import dao_Impl.MySQLBookDAO;
import dao_Impl.MySQLFakturaDAO;
import dao_Impl.MySQLUserDAO;
import dto_objects.BookDTO;
import dto_objects.FakturaDTO;
import dto_objects.UserDTO;

public class Connecter {
	
	private MySQLFakturaDAO fakturaDAO;
	private MySQLBookDAO bookDAO;
	private MySQLUserDAO userDAO;
	private UserDTO currentUser;
	
	public Connecter(){
		try {
			new connector.Connector();
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		fakturaDAO = new MySQLFakturaDAO();
		bookDAO = new MySQLBookDAO();
		userDAO = new MySQLUserDAO();
	}
	
	public boolean validateLogin(String username, String password){
		try {
			currentUser = userDAO.login(username, password);
			return true;
		} catch (DALException e) {
			System.out.println(e.getLocalizedMessage());
			return false;
		}
	}

	public BookDTO findBook(int bookID) throws DALException {
		try {
			return bookDAO.getBook_CopyByID(bookID);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void updateBookCopes(ArrayList<BookDTO> bookList) {
		for (BookDTO bookDTO : bookList) {
			try {
				bookDAO.updateBook_Copy(bookDTO);
			} catch (DALException e) {
				e.printStackTrace(); 
			}
		}
	}

	public void createFaktura(ArrayList<BookDTO> bookList) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Calendar cal = Calendar.getInstance();		
		Calendar calDue = Calendar.getInstance();
		calDue.add(Calendar.DATE, 14);
		
		int fakID = 0;
		try {
			fakID = fakturaDAO.getNewestFakID()+1;
		} catch (DALException | SQLException e1) {
			e1.printStackTrace();
		}
		
		//Creates the Faktura
		FakturaDTO fakturaDTO = new FakturaDTO(currentUser.getUsrID(), fakID, bookList.get(0).getBookID(), 
				dateFormat.format(cal.getTime()), dateFormat.format(calDue.getTime()));
		try {
			fakturaDAO.createUserFaktura(fakturaDTO);
		} catch (DALException e1) {
			e1.printStackTrace();
		}
		
		for (BookDTO bookDTO : bookList) {
			fakturaDTO = new FakturaDTO(currentUser.getUsrID(), fakID, bookDTO.getBookID(), 
					dateFormat.format(cal.getTime()), dateFormat.format(calDue.getTime()));
			try {
				fakturaDAO.createFaktura(fakturaDTO);
			} catch (DALException e) {
				e.printStackTrace();
			}
		}
	}
}
